//
//  CommonClass.m
//  ChaoDaiBao
//
//  Created by EIMS-IOS on 16/1/21.
//  Copyright (c) 2016年 EIMS. All rights reserved.
//

#import "CommonClass.h"

@implementation CommonClass

// 延时
+ (void)completion:(void (^)(bool finish))completion afterDelay:(CGFloat)delay
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(completion)
            completion(YES);
    });
    
}

//获取文字宽高
+ (CGSize)getSizeOfString:(NSString *)string maxWidth:(float)width maxHeight:(float)height withFont:(UIFont *)font
{
    CGSize size = [string boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}


// 设置可变字体
+ (void)setAttributedString:(UILabel *)label rangeStr:(NSString *)rangeStr color:(UIColor *)color font:(UIFont *)font
{
    if (label.text.length > 0)
    {
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:label.text];
        if (color != nil) {
            [attrString addAttribute:NSForegroundColorAttributeName value:color range:[label.text rangeOfString:rangeStr]];
        }
        if (font != nil) {
            [attrString addAttribute:NSFontAttributeName value:font range:[label.text rangeOfString:rangeStr]];
        };
        label.attributedText = attrString;
    }
}

// 设置字体间距
+ (void)setAttributedString:(UILabel *)label lineSpace:(CGFloat)lineSpace
{
    if (label.text.length > 0)
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpace];//调整行间距
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
        label.attributedText = attributedString;
    }
}

//给图片设置颜色
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

// 去掉 html字符串中所有标签
+ (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    
    NSString * text = nil;
    
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    
    html = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    
    return html;
}

// 抖动动画
+ (void)shakeAnimationForView:(UIView *) view
{
    // 获取到当前的View
    CALayer *viewLayer = view.layer;
    
    // 获取当前View的位置
    CGPoint position = viewLayer.position;
    
    // 移动的两个终点位置
    CGPoint x = CGPointMake(position.x + 10, position.y);
    CGPoint y = CGPointMake(position.x - 10, position.y);
    
    // 设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    
    // 设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    // 设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    
    // 设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    
    // 设置自动反转
    [animation setAutoreverses:YES];
    
    // 设置时间
    [animation setDuration:.06];
    
    // 设置次数
    [animation setRepeatCount:3];
    
    // 添加上动画
    [viewLayer addAnimation:animation forKey:nil];
}

// 获取最近的年份
+ (NSArray *)getLatesNumbserYears:(NSInteger)num
{
    NSMutableArray *years=[NSMutableArray array];
    
    //获得系统时间
    NSDate * senddate=[NSDate date];
    //获得系统日期
    NSCalendar * cal=[NSCalendar currentCalendar];
    
    for(NSInteger i=0;i>=-2;i--)
    {
        NSDate *calculateDate=[self setCalculateMonth:i InDate:senddate];
        
        NSDateComponents *comps = [cal components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:calculateDate];
        
        [years addObject:[NSString stringWithFormat:@"%ld",(long)[comps year]]];
    }
    return years;
}

//获取增加年份后的日期
+ (NSDate *)setCalculateMonth:(NSInteger)year InDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:year];
    return [calendar dateByAddingComponents:comps toDate:date options:0];
}

//获取增加天数后的日期
+ (NSDate *)getCalculateDay:(NSInteger)day InDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:day];
    return [calendar dateByAddingComponents:comps toDate:date options:0];
}

//获取某个日期所在年份的天数
+ (NSUInteger)getNumberOfDaysOneYear:(NSDate *)date
{
    NSCalendar *calender = [NSCalendar currentCalendar];
    
    NSRange range = [calender rangeOfUnit:NSDayCalendarUnit
                     
                                   inUnit: NSYearCalendarUnit
                     
                                  forDate: date];
    return range.length;
    
}

//获取当某个日期所在月份天数
+ (NSUInteger)getNumberOfDaysOneMonth:(NSDate *)date
{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit
                     
                                   inUnit:NSMonthCalendarUnit
                     
                                  forDate:date];
    
    return range.length;
    
}


//单位转让
+ (NSString *)unitConversion:(double)amount
{
    if (amount < 10000) {
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
        [formatter setPositiveFormat:@"###,##0.00;"];
        return [formatter stringFromNumber:[NSNumber numberWithDouble:amount]];
//        return [NSString stringWithFormat:@"%.2f",amount];
    }
    else if (amount >= 10000 && amount < 100000000) {
        
        return [NSString stringWithFormat:@"%.2f万",amount / 10000.0];
    }else {
        
        return [NSString stringWithFormat:@"%.2f亿",amount / 100000000];
    }
}

//获取金额单位
+ (NSString *)getAmountUnit:(CGFloat)amount
{
    if (amount < 10000) {
        return @"元";
    }
    else if (amount >= 10000 && amount < 100000000) {
        
        return @"万元";
    }else {
        
        return @"亿元";
    }
}

//金额格式转让
+ (NSString *)formatConversion:(double)amount type:(NSInteger)type
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    
    switch (type) {
        case 1:
            [formatter setPositiveFormat:@"###,##0.00元;"];
            break;
        case 2:
            [formatter setPositiveFormat:@"￥###,##0.00;"];
            break;
        default:
            [formatter setPositiveFormat:@"###,##0.00;"];
            break;
    }
    
    return [formatter stringFromNumber:[NSNumber numberWithDouble:amount]];
}

//字符串加星号
+ (NSString *)stringToAsterisk:(NSString*)str startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    if (![str isEqual:[NSNull null]] && str != nil)
    {
        if (str.length > startIndex && str.length > endIndex) {
            return [NSString stringWithFormat:@"%@****%@",[str substringToIndex:startIndex],[str substringFromIndex:str.length-endIndex]];
        }else
        {
            return str;
        }

    }else
        return @"";
}

//获取加星后的用户名
+ (NSString *)getAsteriskUserName {
    if (AppDelegateInstance.userInfo == nil) {
        return nil;
    }
    if (AppDelegateInstance.userInfo.mobile.length > 0) {
        NSString *mobile = AppDelegateInstance.userInfo.mobile;
        mobile = [NSString stringWithFormat:@"%@****%@",[mobile substringToIndex:3],[mobile substringFromIndex:mobile.length-4]];
        return mobile;
    }else {
        return AppDelegateInstance.userInfo.userName;
    }
}


//获取图片路径
+ (NSString *)getImageUrlPath:(NSString *)path
{
    if (![path isEqual:[NSNull null]] && path != nil)
    {
        if ([path hasPrefix:@"http"]) {
            return path;
        }else{
            return [NSString stringWithFormat:@"%@%@",Baseurl,path];
        }
    }else{
        return  @"";
    }
}

//分享设置
+ (void)shareWithTitle:(NSString *)title Url:(NSString *)url content:(NSString *)content image:(id)image
{
    id<ISSCAttachment> shareImg;
    
    if ([image isKindOfClass:[UIImage class]])
    {
        shareImg = [ShareSDK pngImageWithImage:image];
        
    }else{
        NSString *imagePath = image;
        shareImg = [ShareSDK imageWithUrl:imagePath];
    }
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:@""
                                                image:shareImg
                                                title:title
                                                  url:url
                                          description:@""
                                            mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions: nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess)
                                {
                                    // DLOG(@"分享成功");
                                     [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    // DLOG(@"分享失败,错误码:%ld,错误描述:%@", (long)[error errorCode], [error errorDescription]);
                                     [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [error errorDescription]]];
                                }
                            }];
    
}

//获取今天周几
+ (NSInteger)getCurrentWeekDay
{
    NSDate *now = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSUInteger unitFlags = NSCalendarUnitWeekday | NSCalendarUnitDay |NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    //    NSInteger currentDay = [dateComponent day];
    
    return [dateComponent weekday]; //星期日－－－1  星期一－－－2 星期二－－－3
}

+ (void)buttonEnableWithButton:(UIButton *)button enable:(BOOL)enable {
    if (enable) {
        if ([button isKindOfClass:[ClickButton class]]) {
            ClickButton *clickButton = (ClickButton *)button;
            [clickButton setButtonEnableStaus:YES];
        }else {
            [button setEnabled:YES];
            [button setBackgroundColor:KButtonNormalColor];
            //[button setBackgroundImage:[CommomClass imageWithColor:KColor] forState:UIControlStateNormal];
        }
        
    }else {
        if ([button isKindOfClass:[ClickButton class]]) {
            ClickButton *clickButton = (ClickButton *)button;
            [clickButton setButtonEnableStaus:NO];
        }else {
            [button setEnabled:NO];
            [button setBackgroundColor:KButtonForbidColor];
            //[button setBackgroundImage:[CommomClass imageWithColor:EnableColor] forState:UIControlStateNormal];
        }
    }
}

+ (UserInfo *)loginSuccessWithDictionary:(NSDictionary *)obj {
    
    UserInfo *usermodel = [[UserInfo alloc] init];

    usermodel.userName = [obj objectForKey:@"username"];
    
    if (![NSString isBlank:[obj objectForKey:@"mobile"]]) {
        usermodel.mobile = [obj objectForKey:@"mobile"];
    }
   
    usermodel.userCreditRating = [CommonClass getImageUrlPath:[obj objectForKey:@"creditRating"]];
    usermodel.userImg = [CommonClass getImageUrlPath:[obj objectForKey:@"headImg"]];
    usermodel.userLimit = [obj objectForKey:@"creditLimit"];
    usermodel.isVipStatus = [obj objectForKey:@"vipStatus"];
    usermodel.userId = [obj objectForKey:@"id"];
    usermodel.isLogin = @"1";
    usermodel.accountAmount = [NSString stringWithFormat:@"%.2f", [[obj objectForKey:@"accountAmount"] doubleValue]];
    usermodel.availableBalance = [NSString stringWithFormat:@"%.2f", [[obj objectForKey:@"availableBalance"] doubleValue]];
    usermodel.isEmailStatus = [[obj objectForKey:@"hasEmail"] boolValue];
    usermodel.isMobileStatus = [[obj objectForKey:@"hasMobile"] boolValue];
    usermodel.isPayPasswordStatus = [[obj objectForKey:@"isPayPassword"] boolValue];
    if ([obj objectForKey:@"realityName"] && ![[obj objectForKey:@"realityName"] isKindOfClass:[NSNull class]]) {
        usermodel.realName = [NSString stringWithFormat:@"%@",[obj objectForKey:@"realityName"]];
    }
    usermodel.hasBindCard = [[obj objectForKey:@"isBaoBank"] boolValue];
    usermodel.hasRecharge = [[obj objectForKey:@"is_recharge"] boolValue];

    if ([obj objectForKey:@"spreadLink"] && ![[obj objectForKey:@"spreadLink"] isKindOfClass:[NSNull class]]) {
        usermodel.spreadLink = [NSString stringWithFormat:@"%@",[obj objectForKey:@"spreadLink"]];
    }
 
    AppDelegateInstance.userInfo = usermodel;
    
    return usermodel;
}

// 检测获取的日期是否已到期
+ (BOOL)isExpiredWithDate:(NSString *)value
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"];
    
    NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:[value doubleValue]/1000];
    
    NSDate *senddate = [NSDate date];
    
    //结束时间
    NSDate *enderDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:endDate]];
    //当前时间
    NSDate *senderDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:senddate]];
    
    //得到相差秒数
    NSTimeInterval time=[enderDate timeIntervalSinceDate:senderDate];
    
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minute = ((int)time)%(3600*24)%3600/60;
    int seconds = ((int)time)%(3600*24)%3600%60;
    
    if (days <= 0&&hours <= 0&&minute <= 0&&seconds<=0)
    {//已到期
        return YES;
    }else
    {//未到期
        return NO;
    }
}

+ (NSString *)setBankLogoImageWithBankName:(NSString *)bankNameStr imageView:(UIImageView *)logoImageView {
    NSString *bankName = bankNameStr;
    
    if ([bankNameStr rangeOfString:@"CCB"].length != 0) {
        bankName = @"建设银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_jsyh"];
       
        }else if ([bankNameStr rangeOfString:@"ICBC"].length != 0) {
        bankName = @"工商银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_gsyh"];
            
        
    }else if ([bankNameStr rangeOfString:@"ABC"].length != 0) {
        bankName = @"农业银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_nyyh"];
       
       
    }else if ([bankNameStr rangeOfString:@"BOC"].length != 0) {
        bankName = @"中国银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_zgyh"];
        
    }else if ([bankNameStr rangeOfString:@"BCOM"].length != 0) {
        bankName = @"交通银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_jtyh"];
        
    }else if ([bankNameStr rangeOfString:@"CIB"].length != 0) {
        bankName = @"兴业银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_xyyh"];
        
       
    }else if ([bankNameStr rangeOfString:@"CITIC"].length != 0) {
        bankName = @"中信银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_zxyh"];
    }else if ([bankNameStr rangeOfString:@"CEB"].length != 0) {
        bankName = @"光大银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_gdyh"];
        
        
    }else if ([bankNameStr rangeOfString:@"SZPAB"].length != 0) {
        bankName = @"平安银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_payh"];
        
    }else if ([bankNameStr rangeOfString:@"PSBC"].length != 0) {
        bankName = @"邮政银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_yzyh"];
    }else if ([bankNameStr rangeOfString:@"BOS"].length != 0) {
        bankName = @"上海银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_shyh"];
    }else if ([bankNameStr rangeOfString:@"SPDB"].length != 0) {
        bankName = @"浦发银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_pfyh"];
    }else if ([bankNameStr rangeOfString:@"CMBC"].length != 0) {
        bankName = @"民生银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_msyh"];
        
       
    }else if ([bankNameStr rangeOfString:@"BCCB"].length != 0) {
        bankName = @"北京银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_bjyh"];
    }else if ([bankNameStr rangeOfString:@"GDB"].length != 0) {
        bankName = @"广发银行";
        if (!logoImageView) {
            return bankName;
        }
        logoImageView.image = [UIImage imageNamed:@"BankLogo_gfyh"];
    }

    return bankName;
}


@end
